package gui;

import gameObjects.Castle;
import gameObjects.Unit;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JOptionPane;

public class MouseCastleMenu implements MouseListener{

	CastleMenu castleMenu; 

	public MouseCastleMenu(CastleMenu castleMenu){
		this.castleMenu=castleMenu;
	}

	@Override
	public void mouseClicked(MouseEvent e) {

		if (e.getSource().equals(castleMenu.infantryLabel)){
			buyUnit("INFANTRY");
		}
		else if (e.getSource().equals(castleMenu.pikemanLabel)){
			buyUnit("PIKEMAN");
		}
		else if (e.getSource().equals(castleMenu.cavalryLabel)){
			buyUnit("CAVALRY");
		}
		else if(e.getSource().equals(castleMenu.okButton)){
			castleMenu.setVisible(false);
		}
		else{
			buyUpgrade(e.getSource());
		}

	}

	private void buyUnit(String unitType){

		Unit unit = castleMenu.connector.buyUnit(unitType, castleMenu.player);
		if (unit != null){
			castleMenu.mainWindow.addUnit(unit);
			castleMenu.castle= castleMenu.connector.getCastle(castleMenu.player);
			castleMenu.goldLabel.setText(String.valueOf(castleMenu.castle.getGold()));
			JOptionPane.showMessageDialog(castleMenu, "You bought "+ unitType);
		}
		else{
			JOptionPane.showMessageDialog(castleMenu, "Not enough gold to buy "+ unitType);
		}
	}

	private void buyUpgrade(Object object ){
		UpgradeLabel upgradeLabel = (UpgradeLabel) object;

		if (castleMenu.connector.buyUpgrade(castleMenu.player,upgradeLabel.upgradeIndex) ){

			if(castleMenu.player.equalsIgnoreCase("ORANGE")){
				Castle castle =castleMenu.connector.getCastle("ORANGE");
				castleMenu.castle = castle;
				castleMenu.mainWindow.castleOrange.setGameObject(castle);
			}
			else{
				Castle castle =castleMenu.connector.getCastle("BLUE");
				castleMenu.castle = castle;
				castleMenu.mainWindow.castleBlue.setGameObject(castle);
			}
			castleMenu.update();

			JOptionPane.showMessageDialog(castleMenu, 
					"You bought upgrade: "+upgradeLabel.upgrade.getName()+" for "+upgradeLabel.upgrade.getPrice() );
		}
		else{
			JOptionPane.showMessageDialog(castleMenu, "Upgrade is too expensive.");
		}
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		

	}

	@Override
	public void mouseExited(MouseEvent e) {
		

	}

	@Override
	public void mousePressed(MouseEvent e) {
		

	}

	@Override
	public void mouseReleased(MouseEvent e) {

	}

}
